<template>
  <div id="root">
    <div class="item">
      <TopMemu :back-icon="BackButtonShow">
        <component :is="topMemu.TitleElement" />
      </TopMemu>
      <RouterView />
    </div>
    <div class="item">
      <Memu ref="MemuRef"></Memu>
    </div>
  </div>
</template>

<script setup>
// 导入 npm 包
import { getCurrentInstance, defineAsyncComponent, onMounted, ref, watch, reactive, computed, markRaw, readonly } from "vue";
import { RouterLink, RouterView, useRouter } from "vue-router"
import axios from "axios";
// 导入 组件
import Memu from "@/components/Memu/Memu.vue"
import TopMemu from "@/components/TopMemu/TopMemu.vue"
const router = useRouter()

// 菜单，初始化为null，不要改
let MemuRef = ref(null)
// 菜单 初始化到首页,打包成Hbuilder软件后会路径出问题，需要重新设置路径
onMounted(() => {
  router.push("/")
})

// 公共变量中转站
let global_Object = getCurrentInstance().appContext.config.globalProperties

// 返回按钮的点击函数函数
global_Object.$BackView = (ShowMemu = true) => {
  global_Object.$MemuRef.value['showMemu'].value = ShowMemu;
  router.back()
}

// 设置状态栏返回图标的显示Api
let BackButtonShow = ref(false);
global_Object.$BackButton = reactive({ value: false, tip: "设置状态栏返回图标的选项" })

watch(global_Object.$BackButton, (newValue) => {

  if (newValue.value == false) {
    BackButtonShow.value = false
  } else {
    BackButtonShow.value = true
  }
})
//颜色主题
let color_themes = readonly([{ name: "pink", color: "#ff8b91", showName: "粉色" },
{ name: "green", color: "#5bb965", showName: "绿色" },
{ name: "blue", color: "#409eff", showName: "蓝色" },
{ name: "purple", color: "#c684ff", showName: "紫色" }
]); //主题在这里增删，记得和html的类名对应
global_Object.$colorThemes = reactive({
  index: null,
  "color_themes": color_themes,
  setColorTheme: setColorTheme,
  setColorThemeOnClassName: setColorThemeOnClassName,
  Tip: "这里是主题相关的选项和设置"
});
//填索引改主题色
function setColorTheme(index) {
  let color_theme = color_themes[index];
  let html = document.querySelector('html')
  // 删除所有主题
  for (let i = 0; i < color_themes.length; ++i) {
    html.classList.remove(color_themes[i].name)
  }
  // 选择指定的主题
  html.classList.add(color_theme.name);
  // 记录当前主题
  global_Object.$colorThemes.index = index;
}
//填类名改主题色
function setColorThemeOnClassName(ClassName) {
  for (let i = 0; i < color_themes.length; i++) {
    if (color_themes[i].name == ClassName) {
      setColorTheme(i);
    }
  }
}
setColorThemeOnClassName(store.state.ThemeColor)

//夜间模式的检测
// 切换暗黑光明模式的初始化
import { useDark, useToggle } from "@vueuse/core";
import store from "./store/store";
const isDark = useDark({
  selector: "html",
  valueDark: 'dark',
  valueLight: 'light'
});
const toggleDark = useToggle(isDark);
global_Object.$theme = reactive({ tip: "设置日间模式" });  // 不要动

watch(global_Object.$theme, (newValue) => {
  if (newValue.value) {
    toggleDark(false)  //日间
  } else {
    toggleDark(true)  // 夜间
  }
})
global_Object.$theme.value = window.matchMedia('(prefers-color-scheme: light)').matches; // 初始值,可以改这里 true是日间，false是夜间

// 通知API (Plus)
// 塞一个回调函数
function H5Plus(code) {

  if (window.plus) {
    code();
  } else {
    console.warn("未检测到H5+环境,或还未Plus初始化", window.plus);
  }
}

//这俩只能改第一个，第二个不要动，第二个是动态的，也不需要改动
// 菜单视图，可改动
let MemuView_long = "15fr 1fr"
// 菜单视图，不可改动
let MemuViewGridFr = reactive({ value: MemuView_long })

//菜单标题未设置的默认值，不可删除，可改
let topMemuDefautelement = "";
let TopMemuDefautshowIcon = true;
let topMemu = reactive({
  TitleElement: topMemuDefautelement.value,
  showIcon: TopMemuDefautshowIcon
});
global_Object.$topMemu = topMemu; //默认标题
// 设置Top栏元素的函数
global_Object.$setTopElement = (element = defineAsyncComponent(() => { return import('@/components/Public/NullElement/NullElement.vue') })) => {
  topMemu.TitleElement = markRaw(element)
}

onMounted(() => {
  global_Object.$MemuRef = MemuRef; // 菜单

  // 监听菜单是否显示的执行函数，不要轻易改动
  watch(global_Object.$MemuRef.value['showMemu'], (newValue) => {

    if (newValue.value) {
      MemuViewGridFr.value = MemuView_long

    } else {
      MemuViewGridFr.value = '1fr'
    }
  })
})

// 彩蛋
onMounted(() => {
  // console.log("%c恭喜你发现了彩蛋", "font-size: 10px; user-select: none;  color: #fff; border-radius: 8px; padding: 10px 25px;background: linear-gradient(315deg, #cdb4db 0%, #ffafcc 50%, #a2d2ff 100%)");
})

// 音乐
import 自由之翼1 from "./music/自由の翼.mp3"


// 音乐构造函数
function createMusic(files) {
  let music = {};

  // 显示对象本身
  music._print = function () {
    console.log(this);
  }
  // 获取正在选中的索引
  music._getPlayIndex = function () {
    for (let i = 0; i < this.list.length; ++i) {

      if (this.list[i].use == true) {
        return i;
      }
    }
    console.warn("没有选中的歌曲.");
    return null;
  }
  // 播放函数
  music.play = function (open = true) {
    if (this.nowAudio) {
      if (open) {
        //播放音乐
        music.nowAudio.play()
        music.playStatus.value = true;
      } else {
        // 暂停音乐 
        music.nowAudio.pause()
        music.playStatus.value = false;
      }
    } else {
      console.error("没有选择任何音乐");
    }
  }
  // 显示音乐列表
  music.print = function () {
    console.log(this.list);
  }
  // 获取选中音乐的名称
  music.getNowPlayName = function () {
    for (let i = 0; i < this.list.length; i++) {
      if (this.list[i].use == true) {
        return this.list[i].name;
      }
    }
    console.warn("没有选中的歌曲.");
    return null;
  }
  // 在尾部插入音乐
  music.append = function (file, name) {
    if (file != undefined || name != undefined) {
      this.list.push({ file, name, use: false });
    } else {
      console.warn("文件名和名字未传入函数");
    }
  }
  music.insertPlayNext = function(musicFile){
    let now_play_index = this._getPlayIndex()
    if(now_play_index != null){
      console.log("原音乐列表",this.list);
      music.insert(musicFile,now_play_index+1)
      music.UseNext();
    }else {
      console.warn("没有选中的歌曲.");
    }
  }
  // 在指定位置插入音乐
  music.insert = function (_music, index) {
    this.list.splice(index, 0, _music)
  }
  // 在指定位置删除
  music.delete = function (index) {
    this.list.splice(0, index)
  }
  // 选择音乐
  music.use = function (index) {
    for (let i = 0; i < this.list.length; i++) {
      this.list[i].use = false;
    }
    this.list[index].use = true;
    music.playStatus.value = false;
    this.nowAudio = new Audio(this.list[index].file);
    // 播放完成后自动播放下一首
    if(this.useplayType != playType[1] ){
     this.nowAudio.addEventListener('ended',()=>{
      this.UseNext();
     },false)}else{
      this.nowAudio.addEventListener('ended',()=>{
        this.play();
     },false)
     }
  }
  // 选择下一个音乐
  music.UseNext = function () {
    function _contiune_play(index) {
      if (music.playStatus.value == true) {
        music.play(false);
        music.use(index)
        music.play();
      } else {
        music.use(index)
      }
    }
    let now_play_index = this._getPlayIndex()
    // 如果有选择的音乐
    if (now_play_index || now_play_index == 0) {
      // 如果音乐还没到头
      if (this.list.length > now_play_index + 1) {
        _contiune_play(now_play_index + 1)
      } else { //如果到头了
        // 如果播放类型是循环
        if (this.useplayType == playType[0]) {
          // 播放第一个音乐
          _contiune_play(0)
        } else {
          console.log("音乐到头了");
        }
      }
    } else {
      console.warn("没有音乐被选择");
    }
  }
  // 选择上一个音乐
  music.usePre = function () {
    function _contiune_play(index) {
      if (music.playStatus.value == true) {
        music.play(false);
        music.use(index)
        music.play();
      } else {
        music.use(index)
      }
    }
    let now_play_index = this._getPlayIndex()
        // 如果有选择的音乐
    if (now_play_index || now_play_index == 0) {
      // 如果前面没有音乐了
      if(now_play_index == 0){
        console.log("前面没有音乐了")
      }else {
        _contiune_play(now_play_index - 1)
      }
     } else {
      console.warn("没有音乐被选择");
    }
  }
  

  // 播放类型
  let playType = ["循环", '循环一首', '随机']
  music.useplayType = playType[1]  //默认为循环
  music.playStatus = ref(false); //播放状态
  music.show = ref(false); //是否显示播放器 (还在做)
  // 初始化nowplayMusic（现在播放的音乐）
  music.nowAudio = null;
  // 音乐列表
  // 初始化音乐列表
  music.list = reactive([]);
  for (let i = 0; i < files.length; i++) {
    music.append(files[i].file, files[i].name);
  }
  // 构造完成，返回对象
  return music;
}



global_Object.$music = reactive(createMusic([
  { name: "自由之翼1111111", file: 自由之翼1 },
  { name: "2", file: 自由之翼1 },
  { name: "3", file: 自由之翼1 },
  { name: "4", file: 自由之翼1 }]));

// 测试
onMounted(() => {
  global_Object.$music.use(0);
  window.music = global_Object.$music;
})

document.oncontextmenu = function (e) {
      return false
    }
</script>

<style scoped>
#root {
  height: 99.4vh;
  display: grid;
  grid-template-rows: v-bind("MemuViewGridFr.value");

}
</style>
